# -*- coding: utf-8 -*-

from flask import Flask, request, jsonify, render_template
from flask_cors import CORS
import requests
import json
import base64
import hashlib
import random
import os

# 百度云的语音识别API配置
ASR_APP_ID = '116463592'
ASR_API_KEY = 'QbPYR1OLhlF6crM9Wcjbx9YD'
ASR_SECRET_KEY = 'E2aAgUO3VUUW5RWT8xB9SuRkUBR8U6OA'

# 百度云的翻译API配置
TRANSLATE_APP_ID = '116502622'
TRANSLATE_API_KEY = 'DGcwZ7PkO6UshjCKIVpAF3am'
TRANSLATE_SECRET_KEY = '7UgcFdRNOZxgpsuqpf1c7dSLjKFOgHIt'

app = Flask(__name__)
CORS(app)  # 启用CORS

def get_access_token(api_key, secret_key):
    url = f'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={api_key}&client_secret={secret_key}'
    response = requests.get(url)
    if response.status_code == 200:
        return response.json().get('access_token')
    else:
        print(f"获取访问令牌失败: {response.status_code} - {response.text}")
        return None

def recognize_speech(file_path, access_token):
    try:
        with open(file_path, 'rb') as fp:
            audio_data = fp.read()
        
        speech_base64 = base64.b64encode(audio_data).decode('utf-8')
        audio_length = len(audio_data)
        
        url = 'https://vop.baidu.com/pro_api'
        headers = {'Content-Type': 'application/json'}
        params = {
            'format': 'wav',
            'rate': 16000,
            'dev_pid': 80001,
            'channel': 1,
            'token': access_token,
            'cuid': 'your_unique_user_id',
            'len': audio_length,
            'speech': speech_base64
        }
        
        response = requests.post(url, headers=headers, data=json.dumps(params))
        result = response.json()
        
        if result.get('err_no') == 0:
            return result.get('result')[0]
        else:
            print(f"语音识别失败，错误信息: {result.get('err_no')} - {result.get('err_msg')}")
            return None
    except Exception as e:
        print(f"识别语音时发生错误: {e}")
        return None

def generate_sign(text, salt, secret_key):
    sign_str = TRANSLATE_APP_ID + text + salt + secret_key
    sign = hashlib.md5(sign_str.encode('utf-8')).hexdigest()
    return sign

def translate_text(text, access_token, from_lang='zh', to_lang='en'):
    url = f'https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token={access_token}'
    salt = str(random.randint(32768, 65536))
    sign = generate_sign(text, salt, TRANSLATE_SECRET_KEY)
    params = {
        'q': text,
        'from': from_lang,
        'to': to_lang,
        'appid': TRANSLATE_APP_ID,
        'salt': salt,
        'sign': sign
    }
    headers = {'Content-Type': 'application/json'}
    
    try:
        print(f"请求参数: {params}")  # 打印请求参数
        response = requests.post(url, headers=headers, data=json.dumps(params))
        result = response.json()
        print(f"API返回结果: {result}")  # 打印API的返回内容
        
        if 'result' in result and 'trans_result' in result['result']:
            return result['result']['trans_result'][0]['dst']
        else:
            print(f"翻译失败，错误信息: {result.get('error_code', '')} - {result.get('error_msg', '')}")
            return None
    except Exception as e:
        print(f"翻译时发生错误: {e}")
        return None

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/process_audio', methods=['POST'])
def process_audio_route():
    if 'audio' not in request.files:
        print("没有上传音频文件")  # 调试信息
        return jsonify({'error': '没有上传音频文件'}), 400

    audio_file = request.files['audio']
    print("接收到的文件名:", audio_file.filename)  # 调试信息
    audio_path = os.path.join('audio', audio_file.filename)  # 保存到 audio 目录
    audio_file.save(audio_path)

    asr_token = get_access_token(ASR_API_KEY, ASR_SECRET_KEY)
    if asr_token:
        speech_text = recognize_speech(audio_path, asr_token)
        if speech_text:
            print(f'识别结果: {speech_text}')
            translate_token = get_access_token(TRANSLATE_API_KEY, TRANSLATE_SECRET_KEY)
            if translate_token:
                translated_text = translate_text(speech_text, translate_token)
                return jsonify({
                    'recognizedText': speech_text,
                    'translatedText': translated_text
                })
            else:
                return jsonify({'error': '获取翻译访问令牌失败'}), 500
        else:
            return jsonify({'error': '语音识别失败'}), 500
    else:
        return jsonify({'error': '获取语音识别访问令牌失败'}), 500

if __name__ == '__main__':
    os.makedirs('audio', exist_ok=True)  # 确保保存音频的目录存在
    app.run(debug=True)